package com.dragon.concurrent.demo.suspend;

/**
 * 当一个线程调用了suspend()方法的时候它还是运行状态（RUNNABLE）。
 *
 * @author dragon
 * @version V1.0.0-RELEASE
 * @date 2019/6/1 17:42
 */
public class ThreadStateTest {

    public static void main(String[] args) {
        Thread1 thread1 = new Thread1();
        Thread2 thread2 = new Thread2();
        thread1.setThread2(thread2);
        thread1.start();
        thread2.start();
    }
}

//Thread1负责打印所有线程的状态。
class Thread1 extends Thread {
    private Thread2 t2;

    public void setThread2(Thread2 t2) {
        this.t2 = t2;
    }

    @Override
    public void run() {
        System.out.println("进入t1线程");
        for (int i = 0; i < 6; i++) {
            try {
                System.out.println("t1 的状态： " + getState());
                System.out.println("t2 的状态： " + t2.getState());
                System.out.println();

                if (i == 3) {
                    //恢复t2的运行。
                    t2.resume();
                }

                //为了减少打印次数，所以t1每打印一次睡1秒
                Thread.sleep(1000);
            } catch (InterruptedException e) {

            }
        }

    }
}

class Thread2 extends Thread {
    @Override
    public void run() {
        System.out.println("进入t2线程，挂起");
        //将线程挂起。让t1来控制它的恢复运行。
        suspend();

        System.out.println("t2已经恢复运行");
        System.out.println("t2正在打印1");
        System.out.println("t2正在打印2");
        System.out.println("t2正在打印3");


        System.out.println("t2线程结束");
    }
}
